package com.sicilin.system.user.action;

import com.sicilin.common.ajax.vo.AjaxResponse;
import com.sicilin.common.enums.ResultStateEnum;
import com.sicilin.common.exception.BusinessException;
import com.sicilin.common.json.datatable.DataTableRequest;
import com.sicilin.common.json.datatable.DataTableResponse;
import com.sicilin.common.json.easyui.vo.DatagridResponse;
import com.sicilin.common.page.PageObject;
import com.sicilin.common.page.PageUtils;
import com.sicilin.po.TSysUser;
import com.sicilin.po.TSysUserRole;
import com.sicilin.system.login.dto.LoginUser;
import com.sicilin.system.login.service.LoginService;
import com.sicilin.system.role.dto.Role;
import com.sicilin.system.user.dto.User;
import com.sicilin.system.user.service.UserRoleService;
import com.sicilin.system.user.service.UserService;
import com.sicilin.system.user.util.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;


@Controller
@RequestMapping("/userAction")
public class UserAction {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private LoginService loginService;

    @RequestMapping(value = "/searchUserLimit.json",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("system:user:search")
    public DatagridResponse searchUserLimit(@RequestParam("text")String text, HttpServletRequest request, HttpServletResponse response)throws Exception{
        PageObject<User> pageObject = PageUtils.initPageObject(request);
        int companyId = loginService.getCurrentUser().getCompanyId();
        userService.searchUserWithPage(pageObject,text,companyId);
        return PageUtils.ToEasyUIDatagrid(pageObject);
    }

    @RequestMapping(value = "/searchUserLimit.json",method = RequestMethod.POST,params={"requestType=DataTable"})
    @ResponseBody
    @RequiresPermissions("system:user:search")
    public DataTableResponse searchUserLimit(@RequestBody DataTableRequest request)throws Exception{
        PageObject<User> pageObject = PageUtils.initPageObject(request);
        int companyId = loginService.getCurrentUser().getCompanyId();
        userService.searchUserWithPage(pageObject,request.getSearch().getValue(),companyId);
        return PageUtils.toDataTables(pageObject,request.getDraw());
    }


    @RequestMapping(value = "/saveUser.json",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("system:user:save")
    public AjaxResponse saveUser(@RequestBody TSysUser user)throws Exception{
        LoginUser loginUser = loginService.getCurrentUser();
        TSysUser saveUser = userService.saveUser(user.getAccount(),user.getName(),user.getAccount()+"123",user.getTelephone(),user.getSex(),loginUser.getCompanyId(),user.getEmail(),user.getQq(),user.getAddress());
        User userVo = new User();
        BeanUtils.copyProperties(saveUser,userVo);
        return new AjaxResponse(userVo);
    }

    @RequestMapping(value="/saveUser.json",method = RequestMethod.POST,params = {"admin=true"})
    @ResponseBody
    @RequiresPermissions({"system:user:save","admin"})
    public AjaxResponse saveUserByAdmin(@RequestBody TSysUser user) throws Exception{
        TSysUser saveUser = userService.saveUser(user.getAccount(),user.getName(),user.getAccount()+"123",user.getTelephone(),user.getSex(),user.getCompanyId(),user.getEmail(),user.getQq(),user.getAddress());
        User userVo = new User();
        BeanUtils.copyProperties(saveUser,userVo);
        return new AjaxResponse(userVo);
    }

    @RequestMapping(value = "/updateUser.json",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("system:user:update")
    public AjaxResponse updateUser(@RequestBody User user)throws Exception{
        user = userService.updateUser(user);
        return new AjaxResponse(user);
    }

    @RequestMapping(value = "/getUserRole.json",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("system:user:search")
    public DatagridResponse<Role> getUserRole(@RequestParam("userId")Integer userId)throws Exception{
        List<Role> roles = userRoleService.getUserRole(userId);
        DatagridResponse<Role> roleDatagridResponse = new DatagridResponse<Role>(roles.size(),roles);
        return roleDatagridResponse;
    }

    @RequestMapping(value = "/getUserOweRole.json",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("system:user:search")
    public DatagridResponse<Role> getUserOweRole(@RequestParam("userId")Integer userId)throws Exception{
        int maxLevel = UserUtils.getMaxRoleLevel(loginService.getCurrentUser());
        if(loginService.isAdmin()){
            maxLevel = 0;
        }
        List<Role> roles = userRoleService.getUserOweRole(userId,maxLevel);
        DatagridResponse<Role> roleDatagridResponse = new DatagridResponse<Role>(roles.size(),roles);
        return roleDatagridResponse;
    }


    @RequestMapping(value = "/addUserRole.json",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("system:user:addUserRole")
    public AjaxResponse addUserRole(@RequestBody Set<TSysUserRole> userRoles)throws Exception{
        if(userRoles == null || userRoles.isEmpty()
                || (userRoles.size() == 1 && userRoles.contains(null))
                ){throw new BusinessException("没有需要添加的用户角色！");}
        int maxLevel = UserUtils.getMaxRoleLevel(loginService.getCurrentUser());
        return new AjaxResponse(userRoleService.addUserRoleList(userRoles,maxLevel));
    }

    @RequestMapping(value = "/removeUserRole.json",method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("system:user:removeUserRole")
    public AjaxResponse removeUserRole(@RequestBody Set<TSysUserRole> userRoleSet) throws Exception{
        if(userRoleSet == null || userRoleSet.isEmpty()
                || (userRoleSet.size() == 1 && userRoleSet.contains(null))
                ){throw new BusinessException("没有需要移除的用户角色！");}
        int maxLevel = UserUtils.getMaxRoleLevel(loginService.getCurrentUser());
        return new AjaxResponse(ResultStateEnum.instances(userRoleService.removeUserRoleList(userRoleSet,maxLevel)));
    }


    @RequestMapping(value = "/switchStatus.json",method = RequestMethod.POST,params = {"enable"})
    @ResponseBody
    @RequiresPermissions("system:user:switchStatus")
    public AjaxResponse enableUser(@RequestParam("userId") int userId)throws Exception{
        LoginUser user = loginService.getCurrentUser();
        int companyid = user.getCompanyId();
        return new AjaxResponse(ResultStateEnum.instances(userService.enableUser(userId,companyid)));
    }

    @RequestMapping(value = "/switchStatus.json",method = RequestMethod.POST,params = {"disable"})
    @ResponseBody
    @RequiresPermissions("system:user:switchStatus")
    public AjaxResponse disableUser(@RequestParam("userId") int userId)throws Exception{
        LoginUser user = loginService.getCurrentUser();
        int companyid = user.getCompanyId();
        return new AjaxResponse(ResultStateEnum.instances(userService.disableUser(userId,companyid)));
    }
}
